package cn.sjxy.apiAdmin;

import cn.sjxy.baseLib.AjaxResult;
import cn.sjxy.baseLib.SjuException;
import cn.sjxy.config.mvcExtend.NeedAdminLogin;
import cn.sjxy.mapper.Mp_BookInfo;
import cn.sjxy.mapper.Mp_BookType;
import cn.sjxy.model.Md_BookInfo;
import cn.sjxy.model.Md_BookType;
import cn.sjxy.service.Sv_BookInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * 管理员端 - 图书管理API
 */
@RestController
@Validated
@Api(tags = "管理员端-图书管理")
public class Ad_BookInfo {

    @Autowired
    private Mp_BookInfo mp_bookInfo;

    @Autowired
    private Mp_BookType mp_bookType;

    @Autowired
    private Sv_BookInfo sv_bookInfo;

    /**
     * 获取图书列表（分页）
     *
     * @param bookName  图书名称（模糊查询）
     * @param typeCode  图书类型
     * @param isSell    是否在售
     * @param pageIndex 页码
     * @param pageSize  每页数量
     * @return
     */
    @GetMapping(value = "/admin/bookInfo/getTable")
    @ApiOperation("获取图书列表")
    @NeedAdminLogin
    public AjaxResult getTable(
            @RequestParam(required = false) String bookName,
            @RequestParam(required = false) String typeCode,
            @RequestParam(required = false) String isSell,
            @RequestParam(defaultValue = "1") Integer pageIndex,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 构建查询条件
        QueryWrapper<Md_BookInfo> wrapper = new QueryWrapper<>();

        // 图书名称模糊查询
        if (bookName != null && !bookName.trim().isEmpty()) {
            wrapper.like("bookName", bookName);
        }

        // 图书类型精确查询
        if (typeCode != null && !typeCode.trim().isEmpty()) {
            wrapper.eq("typeCode", typeCode);
        }

        // 是否在售
        if (isSell != null && !isSell.trim().isEmpty()) {
            wrapper.eq("isSell", isSell);
        }

        // 按添加时间倒序
        wrapper.orderByDesc("addDate");

        // 分页查询
        IPage<Md_BookInfo> page = new Page<>(pageIndex, pageSize);
        page = mp_bookInfo.selectPage(page, wrapper);

        // 填充类型名称
        for (Md_BookInfo bookInfo : page.getRecords()) {
            QueryWrapper<Md_BookType> typeWrapper = new QueryWrapper<>();
            typeWrapper.eq("typeCode", bookInfo.getTypeCode());
            Md_BookType bookType = mp_bookType.selectOne(typeWrapper);
            if (bookType != null) {
                bookInfo.setTypeName(bookType.getTypeName());
            }
        }

        // 返回结果
        AjaxResult result = AjaxResult.success("查询成功");
        result.addTable(page.getRecords());
        result.addPage(page);
        return result;
    }

    /**
     * 获取图书详情
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/admin/bookInfo/getDetail")
    @ApiOperation("获取图书详情")
    @NeedAdminLogin
    public AjaxResult getDetail(@NotNull(message = "ID不能为空") Long id) {
        Md_BookInfo bookInfo = sv_bookInfo.getBookDetail(id);
        AjaxResult result = AjaxResult.success("查询成功");
        result.addKey("entry", bookInfo);
        return result;
    }

    /**
     * 新增图书
     *
     * @param bookInfo
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/admin/bookInfo/insert")
    @ApiOperation("新增图书")
    @NeedAdminLogin
    public AjaxResult insert(@RequestBody Md_BookInfo bookInfo) throws Exception {
        // 检查图书编号是否已存在
        if (sv_bookInfo.isBookCodeExist(bookInfo.getBookCode(), null)) {
            SjuException.appEx("图书编号已存在");
        }

        bookInfo.setAddDate(new Date());
        bookInfo.setUpdateDate(new Date());
        if (bookInfo.getIsSell() == null || bookInfo.getIsSell().isEmpty()) {
            bookInfo.setIsSell("是");
        }
        if (bookInfo.getTotalSellQty() == null) {
            bookInfo.setTotalSellQty(0);
        }

        int result = mp_bookInfo.insert(bookInfo);
        if (result > 0) {
            return AjaxResult.success("新增成功");
        } else {
            SjuException.appEx("新增失败");
            return null;
        }
    }

    /**
     * 修改图书
     *
     * @param bookInfo
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/admin/bookInfo/update")
    @ApiOperation("修改图书")
    @NeedAdminLogin
    public AjaxResult update(@RequestBody Md_BookInfo bookInfo) throws Exception {
        // 检查图书编号是否已存在（排除自己）
        if (sv_bookInfo.isBookCodeExist(bookInfo.getBookCode(), bookInfo.getId())) {
            SjuException.appEx("图书编号已存在");
        }

        bookInfo.setUpdateDate(new Date());

        int result = mp_bookInfo.updateById(bookInfo);
        if (result > 0) {
            return AjaxResult.success("修改成功");
        } else {
            SjuException.appEx("修改失败");
            return null;
        }
    }

    /**
     * 删除图书
     *
     * @param bookCode
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/admin/bookInfo/delete")
    @ApiOperation("删除图书")
    @NeedAdminLogin
    public AjaxResult delete(@NotBlank(message = "图书编号不能为空") String bookCode) throws Exception {
        QueryWrapper<Md_BookInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("bookCode", bookCode);
        int result = mp_bookInfo.delete(wrapper);
        if (result > 0) {
            return AjaxResult.success("删除成功");
        } else {
            SjuException.appEx("删除失败");
            return null;
        }
    }

    /**
     * 图书上架
     *
     * @param id
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/admin/bookInfo/toSell")
    @ApiOperation("图书上架")
    @NeedAdminLogin
    public AjaxResult toSell(@NotNull(message = "ID不能为空") Long id) throws Exception {
        sv_bookInfo.toSell(id);
        return AjaxResult.success("上架成功");
    }

    /**
     * 图书下架
     *
     * @param id
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/admin/bookInfo/toNoSell")
    @ApiOperation("图书下架")
    @NeedAdminLogin
    public AjaxResult toNoSell(@NotNull(message = "ID不能为空") Long id) throws Exception {
        sv_bookInfo.toNoSell(id);
        return AjaxResult.success("下架成功");
    }
}

